<template>
	<view class="main">

		<!-- 顶部自定义导航 -->
		<minitemtag v-on:pChangeType="changeType"></minitemtag>
		<!-- 顶部选项卡 -->
		<view class="tab-frame" @touchmove.stop.prevent="moveHandle">
			<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
				<view v-for="(item,index) in tabBars" :key="item.channelId" class="nav-item" :class="{current: index === tabCurrentIndex}"
				 :id="'tab'+index" @click="changeTab(index,item.channelId)">{{item.channelName}}</view>
			</scroll-view>
			<view class="nab-icon" @click="nabiconClick">
				<u-icon class="icon" name="list" color="#bcbcbc" size="50"></u-icon>
			</view>
		</view>
		<!-- 列表频道 -->
		<u-popup closeable v-model="listChannel" mode="bottom" length="90%" border-radius="30">
			<view class="channelTxt">
				<view>{{$t('index.popup.AllChannels')}}<text>{{$t('index.popup.ClickChannel')}}</text>
					<view v-show="editcomplete==false" @click="editcompleteClick(0)" class="edit">{{$t('index.popup.edit')}}</view>
					<view v-show="editcomplete==true" @click="editcompleteClick(1)" class="edit">{{$t('index.popup.complete')}}</view>
				</view>
			</view>
			<view class="channelTag">
				<view class="tag-info" v-for="(item,index) in tabBars" :key="item.channelId">
					<u-tag @click="changeTab(index,item.channelId)" type="info" shape="circle" :text="item.channelName" :closeable="item.showdel"
					 @close="tagClick(index,item)" />
				</view>
			</view>
			<view class="channelTxt" v-show="remaining.length>=1">
				<view>{{$t('index.popup.Recommended')}}<text>({{$t('index.popup.ClickFollow')}})</text>
					<view @click="editcompleteClick(3)" class="edit">{{$t('index.popup.addAll')}}</view>
				</view>
			</view>

			<view class="channelTag">
				<view class="tag-info" v-for="(item,index) in remaining" :key="item.channelId">
					<u-tag @click="addClick(index,item)" type="info" shape="circle" :text="item.channelName" />
				</view>
			</view>
		</u-popup>
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="235" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<scroll-view class="panel-scroll-box" :scroll-y="enableScroll" @scrolltolower="loadMore">
						<!-- 
							* 新闻列表 
							* 和nvue的区别只是需要把uni标签转为weex标签而已
							* class 和 style的绑定限制了一些语法，其他并没有不同
						-->
						<u-empty v-if="tabItem.newsList.length==0" :text="$t('index.backgroundTitle')" mode="news"></u-empty>
						<view v-for="(item, index) in tabItem.newsList" :key="index" class="news-item" @click="navToDetails(item)">
							<view v-if="!item.room_cover" style="border-bottom: 1rpx solid #e6eaf3;padding-bottom: 20rpx;">
								<text :class="['title', 'title'+item.show_type]">{{item.title}}</text>
								<view v-if="item.show_type!=0" :class="['img-list', 'img-list'+item.show_type, item.cover.length === 1 && item.show_type===2 ? 'img-list-single': '']">
									<view v-for="(imgItem, imgIndex) in item.cover" :key="imgIndex" :class="['img-wrapper', 'img-wrapper'+item.show_type, item.cover.length === 1 && item.show_type===2 ? 'img-wrapper-single': '']">
										<image class="img" :src="'http://pic-asean2.oss-cn-hongkong.aliyuncs.com/'+imgItem.url" mode="widthFix"></image>
										<view class="video-tip" v-if="item.video">
											<image :src="'http://pic-asean2.oss-cn-hongkong.aliyuncs.com/'+item.video.img_url" mode="widthFix"></image>
										</view>
									</view>
								</view>
								<!-- 空图片占位 -->
								<view v-else class="img-empty"></view>
								<view :class="['bot', 'bot'+item.show_type]">
									<text class="author">{{item.copy_from}}</text>
									<text class="time">{{item.comment_count}} {{$t('index.comment')}}</text>
									<text class="time">{{$i18n.locale=='en'?utils.timeTodate('m-d H:i', item.publish_time):utils.friendlyDate(item.publish_time) }}</text>
								</view>
							</view>
							<view v-if="item.room_cover" style="border-bottom: 1rpx solid #e6eaf3;">
								<view class="frame-trxt"><text>{{item.room_name}}</text> {{item.room_describe}}</view>
								<view class="forame-image"><!--  @click="watchClick(1,item.room_id)" -->
									<image :src="item.room_cover" mode=""></image>
									<view class="frame-watch">
										<view class="watchzb">
											<view style="display: inherit;">
												<view style="width: 50rpx;height: 50rpx;display: flex;align-items: center;justify-content: center;">
													<view class="zwyLive" style="--color:white;"></view>
												</view>
											</view>
											<text>{{$t('video.live')}}</text>
										</view>
										<text>{{item.view_count}}{{$t('video.people')}}</text>
									</view>
								</view>
								<view class="bot" style="padding: 20rpx 0;">
									<text class="time">{{item.comment_count}} {{$t('index.comment')}}</text>
									<text class="time">{{$i18n.locale=='en'?utils.timeTodate('m-d H:i', item.time_begin):utils.friendlyDate(item.time_begin) }}</text>
								</view>
							</view>
						</view>
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
	</view>
	</view>
</template>

<script>
	import utils from '@/components/shoyu-date/utils.filter.js';
	import minitemtag from './game.vue';
	import mixAdvert from '@/components/mix-advert/vue/mix-advert';
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	import {
		getLanguage
	} from '@/util/tokeCookien.js'
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	var	enchenj='zh-CN';
	export default { 
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			mixAdvert,
			minitemtag
		},
		data() {
			return {
				editcomplete: false, //编辑/完成
				listChannel: false, //底部侧频道列表展示
				utils: utils, //时间转换
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				remaining: [], //删除的频道
				page_index: 1 //当前页数
			}
		},
		onLoad() {
			// 修改底部导航
			uni.setTabBarItem({
				index: 0,
				text: this.$i18n.messages[this.$i18n.locale].tabBar.home
			});
			uni.setTabBarItem({
				index: 1,
				text: this.$i18n.messages[this.$i18n.locale].tabBar.video
			});
			uni.setTabBarItem({
				index: 2,
				text: this.$i18n.messages[this.$i18n.locale].tabBar.Me
			});
			this.loadTabbars();
		},
		onShow() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			if(enchenj!=this.$i18n.locale){
				enchenj=this.$i18n.locale
				this.loadTabbars();
			}
		},
		methods: {
			moveHandle(){
			    return;
			},
			nabiconClick() {
				this.editcompleteClick(5)
				this.listChannel = true;
			},
			//子组件调用父组件方法
			changeType() {
				this.loadTabbars();
			},
			//切换编辑完成
			editcompleteClick(type) {
				if (type == 0) {
					let tabList = this.tabBars;
					tabList.forEach(item => {
						item.showdel = true
					})
					this.tabBars = tabList;
					this.editcomplete = !this.editcomplete
				} else if (type == 3) {
					for (let item of this.remaining) {
						this.tabBars.push(item)
					}
					this.remaining = []
					uni.removeStorageSync('channelList')
				} else if (type == 1) {
					let tabList = this.tabBars;
					tabList.forEach(item => {
						item.showdel = false
					})
					this.tabBars = tabList;
					this.editcomplete = !this.editcomplete
				}else{
					let tabList = this.tabBars;
					tabList.forEach(item => {
						item.showdel = false
					})
					this.tabBars = tabList;
					this.editcomplete=false
				}

			},
			//删除分类
			tagClick(index, item) {
				this.tabBars.splice(index, 1);
				item.showdel = false
				this.remaining.push(item)
				let data = []
				uni.getStorageSync('channelList') ? data = uni.getStorageSync('channelList') : data = []
				data.push(item.channelId)
				uni.setStorageSync('channelList', data)
			},
			//添加分类
			addClick(index, item) {
				this.remaining.splice(index, 1);
				this.tabBars.push(item)
				let data = uni.getStorageSync('channelList')
				for (let i = 0; i < data.length; i++) {
					if (data[i] == item.channelId) {
						data.splice(i, 1)
					}
				}
				console.log(data)
				uni.setStorageSync('channelList', data)
			},
			//获取分类
			async loadTabbars() {
				let datas = {}
				datas.lang_id = 10
				const res = await this.$myRequest({
					url: '/channel/get-channel-list',
					header: datas
				})
				let tabList = res.data.news_channel;
				let recommend = ''
				getLanguage() == 2 ? recommend = 'Recommend' : recommend = '推荐'
				tabList.unshift({
					"channelId": 9999,
					"channelName": recommend
				})
				let dataLsit = []
				// 取 
				if (uni.getStorageSync('channelList').length >= 1) {
					let ids = uni.getStorageSync('channelList');
					this.remaining = []
					for (const item of tabList) {
						if (!this.in_array(item.channelId, ids)) {
							dataLsit.push(item)
						} else {
							this.remaining.push(item)
						}
					}
				} else {
					dataLsit = tabList
				}
				dataLsit.forEach(item => {
					item.showdel = false
					item.newsList = [];
					item.page_index = 1;
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0; //动画
				})

				this.tabBars = dataLsit;
				this.loadNewsList('add');
			},
			//遍历数组
			in_array(search, array) {
				for (var i in array) {
					if (array[i] == search) {
						return true;
					}
				}
				return false;
			},
			//新闻列表
			async loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				let channel_id = tabItem.channelId //频道id
				let page_size = 5 //每页显示多少条数据
				if (type === 'refresh') {
					this.tabBars[this.tabCurrentIndex].page_index = 1
				}
				let page_index = tabItem.page_index //当前第几页
				var list_URL = ''
				if (channel_id == 9999) {
					list_URL = '/recommend-data/get-list-by-type/' + 3 + '/' + page_size + '/' + page_index
				} else {
					list_URL = '/news/get-news-list/' + channel_id + '/' + page_size + '/' + page_index
				}
				const res = await this.$myRequest({
					url: list_URL,
					header: {}
				})
				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif

				//setTimeout模拟异步请求数据
				setTimeout(() => {
					if (type === 'refresh') {
						tabItem.newsList = []; //刷新前清空数组
					}
					let list = [];
					if(channel_id == 9999){
						let newsslist= res.data.news_list
						res.data.live_list.forEach(item => {
							newsslist.push(item);
						})
						newsslist.sort((a, b) => {
							return Math.random() > .2 ? -1 : 1; //静态数据打乱顺序
						})
						list=newsslist
					}else{
						list = res.data.list
					}
					list.forEach(item => {
						tabItem.newsList.push(item);
					})
					//下拉刷新 关闭刷新动画
					if (type === 'refresh') {
						this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
					}
					//上滑加载 处理状态
					if (type === 'add') {
						tabItem.loadMoreStatus = list.length ==0 ? 2 : 0;
						this.tabBars[this.tabCurrentIndex].page_index++
					}
				}, 1000)
			},
			//新闻详情
			navToDetails(item) {
				if(item.room_cover){
					uni.navigateTo({
						url: `/pages/livedetails/livedetails?roomid=${item.room_id}`
					})
				/* }else if(item.video){
					uni.navigateTo({
						url: `/pages/video/interviewdetails/interviewdetails?newsid=${item.room_id}`
					}) */
				}else{
					uni.navigateTo({
						url: `/pages/details/details?news_id=${item.news_id}`
					})
				}
				
			},

			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e, channelId) {
				if(this.editcomplete==true)return
				this.listChannel = false
				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;
					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 10)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss' scoped>
	page,
	.content {
		background-color: #f8f8f8;
		height: 100%;
		overflow: hidden;
	}

	/* 频道列表 */
	.channelTxt {
		width: 100%;
		padding: 100rpx 15rpx 10rpx 15rpx;

		view {
			color: #080808;
			font-size: 40rpx;
			position: relative;

			text {
				font-size: 25rpx;
				color: #cbcbcb;
			}
 
			.edit {
				position: absolute;
				top: 20rpx;
				right: 50rpx;
				color: #ed4141;
				font-size: 30rpx;
			}
		}
	}

	.channelTag {
		padding: 15rpx;
		display: inline-block;

		.tag-info {
			display: inline-block;
			float: left;
			margin: 15rpx 0 15rpx 30rpx;
		}
	}

	/* 顶部tabbar */
	.tab-frame {
		position: relative;
		.nab-icon {
			background-image: linear-gradient(90deg, rgba(255, 255, 255, 0.7), #ffffff);
			width: 13%;
			height: 90rpx;
			position: absolute;
			right: 0rpx;
			top: 0rpx;
			z-index: 10;

			.icon {
				margin: 17rpx;
				margin-right: 0rpx;
			}
		}
	}

	.nav-bar {
		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		width: 90%;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			display: inline-block;
			/* width: 120upx; */
			height: 90upx;
			padding: 0 20rpx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #ed4141;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: #ed4141;

			&:after {
				width: 50%;
			}
		}
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	/**
	 * 新闻列表 直接拿的nvue样式修改，,
	 * 一共需要修改不到10行代码, 另外px需要直接修改为upx，只有单位不一样，计算都是一样的
	 * 吐槽：难道不能在编译的时候把nuve中的upx转为px? 这样就不用修改单位了
	 */
	.video-wrapper {
		width: 100%;
		height: 440upx;

		.video {
			width: 100%;
		}
	}

	view {
		display: flex;
		flex-direction: column;
	}

	.img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 修改结束 */

	/* 新闻列表  emmm 仅供参考 */
	.news-item {
		position: relative;
		width: 750upx;
		padding: 24upx 30upx 0 30upx;
		border-bottom-width: 1px;
		border-color: #eee;
		background-color: #fff;
		.frame-trxt {
			font-size: 35rpx;
			padding-bottom: 10rpx;

			text {
				font-weight: 800;
				padding-right: 30rpx;
			}
		}
		.forame-image {
			position: relative;
		
			image {
				border-radius: 10rpx;
				width: 100%;
				height: 400rpx;
			}
		
			.frame-watch {
				position: absolute;
				padding-right: 20rpx;
				top: 20rpx;
				left: 20rpx;
				height: 60rpx;
				border-radius: 15rpx;
				font-size: 25rpx;
				line-height: 60rpx;
				color: #fff;
				background-color: rgba($color: #000000, $alpha: 0.4);
				display: inline-block;
		
				text {
					margin-left: 20rpx;
				}
		
				.watchzb {
					border-radius: 15rpx;
					display: inline-block;
					background-color: #ed4141;
					padding: 0 10rpx;
		
					text {
						margin: 0;
					}
				}
		
		
			}
		}
	}

	.title {
		font-size: 32upx;
		color: #303133;
		line-height: 46upx;
	}

	.bot {
		flex-direction: row;
	}

	.author {
		font-size: 26upx;
		color: #aaa;
	}

	.time {
		font-size: 26upx;
		color: #aaa;
		margin-left: 20upx;
	}

	.img-list {
		flex-shrink: 0;
		flex-direction: row;
		background-color: #fff;
		width: 220upx;
		height: 140upx;
	}

	.img-wrapper {
		flex: 1;
		flex-direction: row;
		height: 140upx;
		position: relative;
		overflow: hidden;
	}

	.img {
		flex: 1;
		object-fit: cover;
	}

	.img-empty {
		height: 20upx;
	}

	/* 图在左 */
	.img-list1 {
		position: absolute;
		left: 30upx;
		top: 24upx;
	}

	.title1 {
		padding-left: 240upx;
	}

	.bot1 {
		padding-left: 240upx;
		margin-top: 20upx;
		margin-bottom: 20rpx;
	}

	/* 图在右 */
	/* .img-list2 {
		position: absolute;
		right: 30upx;
		top: 24upx;
	}

	.title2 {
		padding-right: 230upx;

	}

	.bot2 {
		margin-top: 20upx;
	} */

	/* 底部3图 */
	.img-list3 {
		width: 700upx;
		margin: 16upx 0upx;
	}

	.img-wrapper3 {
		margin-right: 4upx;
	}

	/* 底部大图 */
	.img-list-single {
		width: 690upx;
		height: 250upx;
		margin: 16upx 0upx;
	}

	.img-wrapper-single {
		height: 250upx;
		margin-right: 0upx;
	}

	.video-tip {
		position: absolute;
		left: 0;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, .3);
	}

	.video-tip-icon {
		width: 60upx;
		height: 60upx;
	}
</style>
